package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type serverLinkInfo struct {
	toServerName string
	t            int
}

func getGraph(rd *bufio.Reader) map[string][]*serverLinkInfo {
	//serverNum := 0
	dataLineNum := 0
	line, _, _ := rd.ReadLine()
	split := strings.Split(string(line), " ")
	//serverNum, _ = strconv.Atoi(split[0])
	dataLineNum, _ = strconv.Atoi(split[1])

	server2ServerGraph := make(map[string][]*serverLinkInfo)

	for i := 0; i < dataLineNum; i++ {
		line, _, _ := rd.ReadLine()

		split := strings.Split(string(line), " ")

		serverName := split[0]
		toServerName := split[1]
		startTime := split[2]
		t, _ := strconv.Atoi(startTime)

		_, ok := server2ServerGraph[serverName]
		if !ok {
			server2ServerGraph[serverName] = make([]*serverLinkInfo, 1)
			server2ServerGraph[serverName][0] = &serverLinkInfo{
				toServerName: toServerName,
				t:            t,
			}

		} else {
			info := &serverLinkInfo{
				toServerName: toServerName,
				t:            t,
			}
			server2ServerGraph[serverName] = append(server2ServerGraph[serverName], info)
		}
	}

	return server2ServerGraph
}

func dfsFindServer(allReadyFind map[string]struct{}, graph map[string][]*serverLinkInfo, t int, serverName, toServerName string) int {
	infos, ok := graph[serverName]
	if !ok {
		return 0
	}
	_, ok = allReadyFind[serverName]

	if ok {
		return 0
	}
	allReadyFind[serverName] = struct{}{}
	for i := 0; i < len(infos); i++ {
		if infos[i].toServerName == toServerName {
			return infos[i].t + t
		}

		if ret := dfsFindServer(allReadyFind, graph, t+infos[i].t, infos[i].toServerName, toServerName); ret != 0 {
			return t + ret
		}
	}
	delete(allReadyFind, serverName)
	return 0
}

func replyAnswer(graph map[string][]*serverLinkInfo, rd *bufio.Reader) {
	line, _, _ := rd.ReadLine()
	questNum, _ := strconv.Atoi(string(line))
	allReadyFind := make(map[string]struct{})
	for i := 0; i < questNum; i++ {
		line, _, _ := rd.ReadLine()
		split := strings.Split(string(line), " ")
		serverName := split[0]
		toServerName := split[1]

		if t := dfsFindServer(allReadyFind, graph, 0, serverName, toServerName); t == 0 {
			fmt.Println("INF")
		} else {
			fmt.Println(strconv.Itoa(t))
		}
	}
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	graph := getGraph(reader)
	replyAnswer(graph, reader)

}
